package main

import (
	"gitee.com/jokces/kit/ginutil"
	"gitee.com/jokces/kit/global"
	"gitee.com/jokces/kit/global/admin/conf"
	sysApi "gitee.com/jokces/kit/global/admin/http"
	_ "gitee.com/jokces/kit/global/admin/service"
	"gitee.com/jokces/kit/global/glconf"
	"gitee.com/jokces/kit/runner"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func main() {
	config := conf.InitConfig()
	global.BootStrap(config)
	defer global.Close()

	//sysService.New()

	//启动http服务
	if err := runner.RunServer(NewAdminHttpServer(global.GetCfg()),
		runner.WithListenAddr("0.0.0.0:46001")); err != nil {
		log.Printf("runner exit: %v\n", err)
	}
}

func NewAdminHttpServer(c *glconf.Config) runner.Server {
	midFlag := ginutil.MStd
	if c.Release() {
		midFlag = ginutil.MRelease | ginutil.MTraceId | ginutil.MRecoverLogger
	}
	httpHandler := ginutil.DefaultEngine(midFlag)

	//配置跨域
	httpHandler.Use(core())

	router := sysApi.New()

	//注册所有的路由
	{
		router.RegisterAdminRouter(httpHandler)
		router.RegisterBaseRouter(httpHandler)
	}

	return runner.NewHttpServer(httpHandler)
}

// 解决跨域问题
func core() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		context.Header("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Headers", "Content-Type,AX-Client-Token,AX-Access-Token,skipToken,X-CSRF-Token, Authorization, Token")
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		context.Header("Access-Control-Allow-Credentials", "true")
		//放行索引options
		if method == "OPTIONS" {
			context.AbortWithStatus(http.StatusNoContent)
		}
		//处理请求
		context.Next()
	}
}
